import { useMemberStore } from '@/stores'
import GeneralCallbackResult = UniNamespace.GeneralCallbackResult;

const baseURL = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'

const httpInterceptor = {
  invoke(options: Uniapp.RequestOptions) {
    // request 触发前拼接 url
    if (!options.url.startsWith('http')) {
      options.url = baseURL + options.url
    }
    // 请求超时，默认 60s ，改为 10
    options.timeout = 10000
    // 添加小程序端请求头标识
    options.header = {
      ...options,
      'source-client': 'miniapp',
    }
    // 添加token
    const memberStore = useMemberStore()
    const token = memberStore.profile?.token
    console.log("token::", token)
    if (token) {
      options.header = {
        ...options,
        'Authrization': token
      }
    }
  },
  success(args) {
    // 请求成功后，修改code值为1
    args.data.code = 1
  },
  fail(err) {
    console.log('interceptor-fail', err)
  },
  complete(res) {
    console.log('interceptor-complete', res)
  },
}

// 添加请求拦截器
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

interface Data<T> {
  code: string
  msg: string
  result: T
}

export const http = <T>(options) => {
  // 返回 Promise 对象
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...options,
      // 请求成功
      success(res) {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          // 请求成功，正常放行
          resolve(res.data as Data<T>)
        } else if (res.statusCode === 401) {
          // 权限认证，需要重新登录
          const store = useMemberStore()
          store.clearProfile()
          uni.navigateTo({ url: '/pages/login/login' })
          reject(res)
        } else {
          uni.showToast({
            icon: 'none',
            duration: 2000,
            title: (res.data as Data<T>).msg || '请求错误',
          })

          reject(res)
        }
      },
      fail(err: GeneralCallbackResult) {
        uni.showToast({
          icon: 'none',
          duration: 2000,
          title: '连接超时，换个网络试试吧',
        })
        reject(err.errMsg)
      },
    })
  })
}
